package org.redis.cluster.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ConcurrentHashMap;

public class ClassUtil {

	private final static ConcurrentHashMap<String,Class<?>> CLASS_MAPPING=new ConcurrentHashMap<String,Class<?>>();
	
	/**
	 * 
	 * @param className
	 * @return
	 * @throws ClassNotFoundException 
	 */
	public static Class<?> forName(String className) throws ClassNotFoundException {
		if(CLASS_MAPPING.contains(className)) {
			return CLASS_MAPPING.get(className);
		}
		
		Class<?> result=Class.forName(className);
		if(CLASS_MAPPING.putIfAbsent(className, result)!=null) {
			return CLASS_MAPPING.get(className);
		}
		
		return result;
	}
	
	/**
	 * 新实例
	 * @param clazz
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static <T> T newInstance(Class<?> clazz) throws InstantiationException, IllegalAccessException {
		return (T) clazz.newInstance();
	}
	
	/**
	 * 新实例
	 * @param clazz
	 * @param constructor
	 * @param parameters
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static <T> T newInstance(Class<?> clazz,Constructor<?> constructor,Object...parameters) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		return (T) constructor.newInstance(parameters);
	}
}